/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.open.api.core.service.processor.base.pre;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import info.peigen.hotpot.business.customer.facade.info.partner.PartnerInfo;
import info.peigen.hotpot.business.customer.facade.info.partner.PartnerTechInfo;
import info.peigen.hotpot.common.core.util.IdUtil;
import info.peigen.hotpot.component.open.api.core.service.processor.base.AbstractOpenApiServiceProcessor;
import info.peigen.hotpot.component.open.api.facade.Api;
import info.peigen.hotpot.component.open.api.facade.order.OpenApiOrder;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessor;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessorServiceContext;
import org.noear.solon.annotation.Component;

import java.nio.charset.StandardCharsets;


/**
 * <b>(OpenApiDecryptProcessor)</b>
 * 解密
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/6/13
 */
@Component
public class OpenApiDecryptProcessor extends AbstractOpenApiServiceProcessor implements OpenApiProcessor {
    @Override
    public Integer level() {
        return 5;
    }

    @Override
    public void execute(OpenApiProcessorServiceContext serviceContext) {
        OpenApiOrder order       = serviceContext.getOrder();
        PartnerInfo  partnerInfo = (PartnerInfo) serviceContext.getPartnerInfo();
        Api api = BeanUtil.copyProperties(order, Api.class)
                .setGid(IdUtil.gid());
        String decrypt = decrypt(partnerInfo.getTech(), order.getEncrypt());
        api.setDecrypt(decrypt);
        serviceContext.setApi(api);
    }

    private String decrypt(PartnerTechInfo tech, String encrypt) {
        return switch (tech.getType()) {
            case RSA -> decryptForRsa(tech.getPartnerPrivateKeyStr(), tech.getPartnerPublicKeyStr(), encrypt);
            case SM2 -> decryptForSm2(tech.getPartnerPrivateKeyStr(), tech.getPartnerPublicKeyStr(), encrypt);
            default -> null;
        };
    }

    private String decryptForRsa(String privateKey, String publicKey, String encrypted) {
        RSA    rsa        = new RSA(privateKey, publicKey);
        String decryptStr = rsa.decryptStr(encrypted, KeyType.PrivateKey);
        return URLDecoder.decode(decryptStr, StandardCharsets.UTF_8);
    }

    private String decryptForSm2(String privateKey, String publicKey, String encrypted) {
        if (StrUtil.startWith(encrypted, "04")) {
            return SmUtil.sm2(privateKey, publicKey)
                    .decryptStr(encrypted, KeyType.PrivateKey);
        }
        return SmUtil.sm2(privateKey, publicKey)
                .decryptStr("04" + encrypted, KeyType.PrivateKey);
    }
}